<template>
  <div class="list-pages white-bg">
    <div class="search-form-box">
      <a-form
        :model="formState"
        name="horizontal_login"
        autocomplete="off"
        @finish="onFinish"
      >
        <a-row :gutter="16">
          <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="12" v-show="expand">
            <a-form-item label="知识库" name="name">
              <a-input
                v-model:value="formState.name"
                placeholder="请输入关键字进行搜索"
              >
              </a-input>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item>
              <div class="search-btn-box" :class="{ pt: expand }">
                <a-button
                  :icon="h(SearchOutlined)"
                  type="primary"
                  html-type="submit"
                  class="search-btn"
                  >查询</a-button
                >
                <a-button
                  :icon="h(ReloadOutlined)"
                  class="reset-btn"
                  @click="resetForm"
                  >清空</a-button
                >
                <a
                  class="expand-btn"
                  style="font-size: 12px; margin-left: 12px"
                  @click="expand = !expand"
                >
                  <template v-if="expand">
                    <UpOutlined />
                  </template>
                  <template v-else>
                    <DownOutlined />
                  </template>
                  {{ expand ? "收起查询" : "展开查询" }}
                </a>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="opt-button-box">
      <!-- <a-button type="primary" class="btn" @click="handleAdd">
        <img src="/icons/common/icon-add.png" class="icon" />问答知识列表</a-button> -->
      <a-button type="primary" class="btn" @click="handleUpload">
        <img src="/icons/common/icon-add.png" class="icon" />
        上传知识文件</a-button
      >
      <!-- <a-button class="btn" @click="handleExport">
        <img src="/icons/common/icon-export.png" class="icon" />
        导出
      </a-button> -->
    </div>
    <div class="table-wrapper" ref="tableRef">
      <a-table
        class="table-box"
        row-key="index"
        :columns="columns"
        :dataSource="tableData"
        :row-class-name="
          (_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        "
        sticky
        :scroll="{ y: true, x: 1100 }"
        :pagination="pagination"
        @change="onChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'file_size'">
            {{ formatFileSize(record?.file_size) }}
          </template>
          <template v-if="column.dataIndex == 'operation'">
            <!-- <a-button type="link" class="link" @click="handleDetail(record)">
              查看
            </a-button> -->
            <!-- <a-button type="link" class="link" @click="handleEdit(record)">
              编辑
            </a-button> -->
            <a-button type="link" class="link" @click="handleAiSend(record.ai_doc_id)">推送给AI</a-button>
            <a-popconfirm title="确认删除?" @confirm="handleDelete(record)">
              <a-button type="link" class="link"> 删除 </a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 上传文档对话框 -->
    <a-modal
      v-model:open="uploadVisible"
      title="上传"
      width="500px"
      @ok="handleUploadOk"
      @cancel="handleUploadCancel"
    >
      <a-form :model="uploadForm" layout="vertical">
        <a-form-item label="名称" required>
          <a-input
            v-model:value="uploadForm.name"
            placeholder="请输入文档名称"
          />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            v-model:value="uploadForm.description"
            placeholder="请输入描述"
            :rows="4"
            show-count
            :maxlength="500"
          />
        </a-form-item>
        <a-form-item label="文件" required>
          <a-upload
            name="file"
            :multiple="false"
            :max-count="1"
            v-model:file-list="fileList"
            :customRequest="customUpload"
            @change="handleChange"
            accept=".pdf,.doc,.docx,.txt,.md"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              选择文件
            </a-button>
          </a-upload>
          <div class="upload-tip">
            支持格式：PDF、DOC、DOCX、TXT、MD，文件大小不超过10MB
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改文档对话框 -->
    <a-modal
      v-model:open="editVisible"
      title="修改"
      width="500px"
      @ok="handleEditOk"
      @cancel="handleEditCancel"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="文档名称" required>
          <a-input v-model:value="editForm.name" placeholder="请输入文档名称" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            v-model:value="editForm.description"
            placeholder="请输入描述"
            :rows="4"
            show-count
            :maxlength="500"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted, onUnmounted } from "vue";
import {
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
  UpOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import { useGlobalStore } from "@/store/modules/global";
import { message } from "ant-design-vue";
import knowledgeApi from "@/api/knowledge";
import systemApi from "@/api/system";
const store = useGlobalStore();
const router = useRouter();

const formState = ref({
  name: "",
  enabled: "",
});

const resetForm = () => {
  formState.value = {
    name: "",
    enabled: "",
  };
  getData();
};
// 自定义上传函数1 - 设备模型
const customUpload = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error("上传失败"));
    }
  } catch (error) {
    console.error("模型文件上传失败:", error);
    onError(error);
  }
};
const handleChange = (info) => {
  const { fileList } = info;
  fileList.value = fileList;

  const status = info.file.status;

  if (status === "done") {
    // 处理上传成功的响应数据
    const response = info.file.response;
    console.log("处理上传成功响应:", response);

    if (response && response.succeeded && response.data) {
      // 更新文件信息，使用API返回的URL
      info.file.url = response.data.url;
      console.log("设置文件URL为:", response.data.url);
    } else {
      console.error("响应格式错误:", response);
    }
  } else if (status === "error") {
    console.error("上传错误:", info.file.error);
  }
};

const windowWidth = ref(window.innerWidth);
const expand = ref(true);

onMounted(async () => {
  windowWidth.value = window.innerWidth;
  if (windowWidth.value > 768) {
    expand.value = true;
  } else {
    expand.value = false;
  }
  window.addEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
    if (windowWidth.value > 768) {
      expand.value = true;
    } else {
      expand.value = false;
    }
  });
  getData();
});

onUnmounted(() => {
  window.removeEventListener("resize", () => {});
});

function onFinish(values) {
  console.log("Success:", values);
  getData();
}

const tableData = ref([]);

const columns = ref([
  {
    dataIndex: "name",
    title: "名称",
    ellipsis: true,
    width: 200,
  },
  {
    dataIndex: "file_size",
    title: "大小",
    width: 120,
  },
  {
    dataIndex: "doc_type",
    title: "格式",
    width: 100,
  },
  {
    dataIndex: "description",
    title: "描述",
    ellipsis: true,
  },
  {
    dataIndex: "created",
    title: "更新时间",
    width: 180,
  },
  {
    dataIndex: "user_real_name",
    title: "上传人",
    width: 120,
  },
  {
    dataIndex: "operation",
    title: "操作",
    width: 220,
    align: "center",
    fixed: "right",
  },
]);

const onChange = (page) => {
  console.log(page);
  current.value = page.current;
  pageSize.value = page.pageSize;
  getData();
};

const current = ref(1);
const pageSize = ref(10);
const total = ref(0);

const pagination = computed(() => ({
  position: ["bottomCenter"],
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  size: "large",
  showTotal: (total) => `共 ${total} 条`,
}));

const handleAdd = () => {
  store.setSubTitle("新增文档");
  router.push("ai-knowledge-management-option");
};

const handleDetail = (data) => {
  store.setSubTitle("查看文档信息");
  router.push(`ai-knowledge-management-detail?id=${data.id}`);
};

const handleEdit = async (data) => {
  store.setSubTitle("编辑文档");
  router.push(`ai-knowledge-management-option?id=${data.ai_doc_id}`);
};

const handleDelete = async (data) => {
  console.log(data, "data");

  try {
    const response = await knowledgeApi.AiDocDelete({
      ai_doc_id: data.ai_doc_id,
    });
    console.log(response, "response");
    if (response) {
      message.success("删除成功");
      getData();
    } else {
      message.error(response.data?.message || "删除失败");
    }
  } catch (error) {
    console.error("删除文档失败:", error);
    message.error("删除失败，请稍后重试");
  }
};

// 表格数据获取方法
const getData = async () => {
  try {
    const params = {
      args: {
        pageIndex: current.value,
        pageSize: pageSize.value,
        keyword: formState.value.name || undefined,
      },
    };

    const response = await knowledgeApi.AiDocPagedList(params);
    console.log(response, "response");
    if (response.data) {
      tableData.value = response.data || [];
      total.value = response.total || 0;
    } else {
      message.error(response.data?.message || "获取数据失败");
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取文档列表失败:", error);
    message.error("获取数据失败，请稍后重试");
    tableData.value = [];
    total.value = 0;
  }
};

// 上传文档功能
const uploadVisible = ref(false);
const uploadForm = ref({
  name: "",
  description: "",
});
const fileList = ref([]);

const handleUpload = () => {
  uploadVisible.value = true;
};
const handleAiSend = async (id) => {
  let params = {
    ai_doc_id: id,
  };
  const res = await knowledgeApi.UploadAiDocToVolcEngineKnowledgebase(params);
  console.log(333, res);
  message.success("推送给AI成功");
  fileList.value = [];
  getData();
};
const handleUploadOk = async () => {
  try {
    if (!uploadForm.value.name) {
      message.error("请输入文档名称");
      return;
    }

    if (fileList.value.length === 0) {
      message.error("请选择要上传的文件");
      return;
    }

    const uploadData = {
      name: uploadForm.value.name,
      description: uploadForm.value.description,
      // 这里需要根据实际API要求处理文件数据
      //files: fileList.value,
      doc_name: fileList.value[0].name,
      doc_type: fileList.value[0].name.split(".")[1],
      file_content_type: fileList.value[0].type,
      file_size: fileList.value[0].size,
      url: fileList.value[0].response.url,
    };

    const response = await knowledgeApi.AiDocCreate(uploadData);
    console.log(111, response);
    if (response.ai_doc_id) {
      uploadVisible.value = false
      handleAiSend(response.ai_doc_id);
    }
    // if (response.data && response.data.success) {
    //   message.success("上传成功");
    //   uploadVisible.value = false;
    //   uploadForm.value = { name: "", description: "" };
    //   fileList.value = [];
    //   getData();
    // } else {
    //   message.error(response.data?.message || "上传失败");
    // }
  } catch (error) {
    console.error("上传文档失败:", error);
    message.error("上传失败，请稍后重试");
  }
};

const handleUploadCancel = () => {
  uploadVisible.value = false;
  uploadForm.value = {
    name: "",
    description: "",
  };
  fileList.value = [];
};

const beforeUpload = (file) => {
  const isValidType = [
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "text/plain",
    "text/markdown",
  ].includes(file.type);
  if (!isValidType) {
    message.error("只能上传 PDF、DOC、DOCX、TXT、MD 格式的文件!");
    return false;
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error("文件大小不能超过 10MB!");
    return false;
  }
  return false; // 阻止自动上传
};

const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

// 编辑文档功能
const editVisible = ref(false);
const editForm = ref({
  name: "",
  description: "",
});

const handleEditOk = async () => {
  try {
    if (!editForm.value.name) {
      message.error("请输入文档名称");
      return;
    }

    const response = await knowledgeApi.AiDocUpdate(editForm.value);

    if (response.data && response.data.success) {
      message.success("修改成功");
      editVisible.value = false;
      editForm.value = { name: "", description: "" };
      getData();
    } else {
      message.error(response.data?.message || "修改失败");
    }
  } catch (error) {
    console.error("编辑文档失败:", error);
    message.error("修改失败，请稍后重试");
  }
};

const handleEditCancel = () => {
  editVisible.value = false;
  editForm.value = {
    name: "",
    description: "",
  };
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 导出功能
const handleExport = async () => {
  try {
    // 构建导出参数，使用当前搜索条件
    const exportParams = {
      current: current.value,
      pageSize: pageSize.value,
    };

    // 只有当字段有值时才添加到参数中
    if (formState.value.name) {
      exportParams.name = formState.value.name;
      exportParams.login_name = formState.value.name;
    }
    if (
      formState.value.feedback_status_id !== undefined &&
      formState.value.feedback_status_id !== null
    ) {
      exportParams.feedback_status_id = parseInt(
        formState.value.feedback_status_id
      );
    }
    if (formState.value.class) {
      exportParams.feedback_category_idArray = [
        parseInt(formState.value.class),
      ];
    }
    if (formState.value.createTime && formState.value.createTime.length === 2) {
      exportParams.create_dateRange = formState.value.createTime;
    }

    console.log("导出参数:", exportParams);

    // 调用导出API
    const response = await knowledgeApi.AiDocExport(exportParams);

    console.log("导出响应:", response);

    if (response && response.file) {
      const fileData = response.file;

      // 处理Base64编码的文件内容
      const base64Content = fileData.fileContents;
      const contentType =
        fileData.contentType ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const fileName = fileData.fileDownloadName || "文档列表_导出.xlsx";

      try {
        // 将Base64字符串转换为二进制数据
        const binaryString = atob(base64Content);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }

        // 创建Blob对象
        const blob = new Blob([bytes], { type: contentType });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = fileName;

        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // 清理URL对象
        window.URL.revokeObjectURL(url);

        message.success("导出成功");
      } catch (decodeError) {
        console.error("文件解码失败:", decodeError);
        message.error("文件解码失败，请稍后重试");
      }
    } else {
      const errorMessage = response?.errors?.[0] || "导出失败";
      console.error("导出失败:", response);
      message.error(errorMessage);
    }
  } catch (error) {
    console.error("导出用户收藏仪器列表失败:", error);
    message.error("导出失败，请稍后重试");
  } finally {
  }
};
</script>
<style lang="less" scoped>
.list-pages {
  height: 100%;
  padding: 0 16px;
  display: flex;
  flex-direction: column;

  .search-box {
    display: flex;
    align-items: center;
    padding: 18px 0;
    flex-wrap: wrap;
    border-bottom: 1px solid #e5e7eb;

    .search-select {
      width: 120px;
    }

    .line {
      width: 1px;
      height: 16px;
      margin: 0 12px;
      background: #bec4ca;

      @media screen and (max-width: 768px) {
        display: none;
      }
    }

    .search-input-box {
      flex: 1;
      display: flex;
      align-items: center;

      @media screen and (max-width: 768px) {
        width: 100%;
        margin-top: 16px;
        justify-content: space-between;
      }
    }

    .search-input {
      flex: 1;
    }

    .search-btn {
      width: 60px;
      height: 32px;
      background: #2776ff;
      border-radius: 4px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 32px;
    }
  }

  .table-wrapper {
    width: 100%;
    flex: 1;
    overflow: hidden;

    .table-box {
      height: 100%;
    }
  }

  .list-box {
    width: 100%;
    box-sizing: border-box;
    padding-top: 16px;
    overflow: auto;
    display: grid;
    gap: 16px;
    margin: 0 auto;
    grid-template-columns: repeat(auto-fill, minmax(261px, 1fr));
    justify-content: space-between;

    .list-item {
      width: 261px;
      background: #ffffff;
      border: 1px solid #e6ebf1;
      border-radius: 8px;
      box-sizing: border-box;
      padding: 8px;
      margin: auto;
      position: relative;
      cursor: pointer;

      &:hover {
        border: 1px solid #2776ff;
        box-shadow: 12px 12px 12px 0px rgba(39, 118, 255, 0.1);
      }

      .item-collect {
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        width: 32px;
        height: 32px;
        background: rgba(0, 0, 0, 0.4) url(@/assets/icon-collet.png) no-repeat
          center center;
        border-radius: 0 8px 0 12px;

        &.cur {
          background: #ffffff url(@/assets/icon-collet-cur.png) no-repeat center
            center;
          border-radius: 0 8px 0 12px;
        }
      }

      .list-img {
        width: 245px;
        height: 249px;
        background: #f3f3f3;
        border: 1px solid #e6ebf1;
        border-radius: 8px;
        box-sizing: border-box;

        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }

      .list-content {
        padding: 14px 0 6px;
        display: flex;
        flex-direction: column;

        .content-title {
          font-family: PingFangSC-Medium;
          font-weight: 500;
          font-size: 16px;
          color: #31323a;
          margin-bottom: 10px;
          line-height: 24px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .content-col {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .col-user {
            display: flex;
            align-items: center;

            .user-img {
              width: 26px;
              height: 26px;
              border-radius: 50%;
            }

            .user-name {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 12px;
              color: #262626;
              line-height: 16px;
              text-align: left;
              font-style: normal;
            }
          }

          .col-date {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #8c8c8c;
            line-height: 16px;
            text-align: center;
            font-style: normal;
          }
        }
      }
    }
  }

  .pagination-box {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
